<?php

namespace app\api\controller;
/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 卖家店铺控制器
 */
class Sellerstore extends MobileSeller
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * @api {POST} api/Sellerstore/store_info 获取店铺信息
     * @apiVersion 1.0.0
     * @apiGroup Sellerstore
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.store_info  店铺信息 （返回字段参考store）
     */
    public function store_info()
    {
        $this->store_info['store_banner'] = get_store_logo($this->store_info['store_banner'], 'store_logo');


	    //店铺头像
	    $this->store_info['store_avatar'] = get_store_logo($this->store_info['store_avatar'], 'store_avatar');

	    //店铺标志
	    $this->store_info['store_logo'] = get_store_logo($this->store_info['store_logo'], 'store_logo');

	    $consult_model = model('consult');
	    /**
	     * 订单成交数量
	     */
	    $order_where=[
		    'order_state'=>['in',['20','30','40']],
		    'refund_state'=>['in',['0','1']],
		    'delete_state'=>0,
		    'store_id'=>$this->store_info['store_id']
	    ];


	    $vrorder_where=[
		    'order_state'=>['in',['20','40']],
		    'refund_state'=>['in',['0','1']],
		    'delete_state'=>0,
		    'store_id'=>$this->store_info['store_id']
	    ];
	    $order_count=model('order')->getOrderNum($order_where);
	    $vrorder_count=model('Vrorder')->getOrderNum($vrorder_where);
	    $this->store_info['order_count']=$vrorder_count+$order_count;

	    //获取交易金额
	    $order_amountcount=model('order')->getOrderAmountNum($order_where);
	    $vrorder_amountcount=model('Vrorder')->getOrderAmountNum($vrorder_where);

	    $this->store_info['order_amountcount']=(string)($order_amountcount+$vrorder_amountcount);
	    /**
	     * 今日交易数量
	     */
	    $start_time=strtotime(date('Y-m-d'));
	    $end_time=strtotime(date('Y-m-d')) + 24 * 3600;
	    $order_where['payment_time']=[['egt',$start_time],['lt',$end_time]];
	    $vrorder_where['payment_time']=[['egt',$start_time],['lt',$end_time]];
	    $totalorder_count=model('order')->getOrderNum($order_where);
	    $totalvrorder_count=model('Vrorder')->getOrderNum($vrorder_where);
	    $this->store_info['totalorder_count']=$totalvrorder_count+$totalorder_count;

	    //获取交易金额
	    $totalorder_amountcount=model('order')->getOrderAmountNum($order_where);
	    $totalvrorder_amountcount=model('Vrorder')->getOrderAmountNum($vrorder_where);

	    $this->store_info['totalorder_amountcount']=(string)($totalorder_amountcount+$totalvrorder_amountcount);
	    //询问数量统计
	    $where = array();
	    $where['store_id'] =  $this->store_info['store_id'];
	    $this->store_info['consult_count'] = $consult_model->getConsultCount($where);
	    /**
	     * 未支付訂單數量
	     */
	    $order_state=[
		    'order_state'=>10,
		    'delete_state'=>0,
		    'store_id'=>$this->store_info['store_id']
	    ];
	    $vrorder_state=[
		    'order_state'=>10,
		    'delete_state'=>0,
		    'store_id'=>$this->store_info['store_id']
	    ];
	    $dai_order_count=model('order')->getOrderNum($order_state);
	    $dai_vrorder_count=model('Vrorder')->getOrderNum($vrorder_state);
	    $this->store_info['dai_order_num']=$dai_order_count+$dai_vrorder_count;;

		//待发货订单
	    $order_state['order_state']=20;
	    $fa_order_count=model('order')->getOrderNum($order_state);
	    $this->store_info['fa_order_num']=$fa_order_count;

	    unset($order_state['order_state']);

	    $quan_order_count=model('order')->getOrderNum($order_state);
	    $this->store_info['quan_order_num']=$quan_order_count;
	    $ppwhere=[
		    'store_id'=>$this->store_info['store_id']
	    ];
	    $pintuan_id=db('Ppintuan')->where($ppwhere)->column('pintuan_id');
	    $this->store_info['ppin_order_count']=0;
	    if($pintuan_id){
		    //获取待成团订单
		    $pwhere=[
			    'pintuanorder_state'=>1,
			    'pintuanorder_isfirst'=>1,
			    'pintuan_id'=>array('in',$pintuan_id)
		    ];
		    $this->store_info['ppin_order_count']=model("Ppintuanorder")->getOnePpintuanorderCount($pwhere);
	    }

	    /**
	     * 待退款
	     */
	    $refundreturn_model = model('refundreturn');
	    $condition = array();
	    $condition['store_id'] = $this->store_info['store_id'];
	    $condition['order_lock'] = 2;
	    $condition['refund_state'] = array('lt', 3);
	    $this->store_info['refund_lock'] = $refundreturn_model->getRefundreturnCount($condition);

	    $goods_model = model('goods');
	    // 出售中的商品
	    $this->store_info['goods_online'] = $goods_model->getGoodsCommonOnlineCount(array('store_id' => session('store_id')));
	    if (config('goods_verify')) {
		    // 等待审核的商品
		    $this->store_info['goods_waitverify'] = $goods_model->getGoodsCommonWaitVerifyCount(array('store_id' => session('store_id')));
		    // 审核失败的商品
		   $this->store_info['goods_verifyfail'] = $goods_model->getGoodsCommonVerifyFailCount(array('store_id' => session('store_id')));
	    }
	    // 仓库待上架的商品
	    $this->store_info['goods_offline'] = $goods_model->getGoodsCommonOfflineCount(array('store_id' => session('store_id')));
	    // 违规下架的商品
	   $this->store_info['goods_lockup'] = $goods_model->getGoodsCommonLockUpCount(array('store_id' => session('store_id')));

	    ds_json_encode(10000, '',array('store_info' => $this->store_info));
    }

    /**
     * @api {POST} api/Sellerstore/store_edit 编辑店铺信息
     * @apiVersion 1.0.0
     * @apiGroup Sellerstore
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} store_qq QQ
     * @apiParam {String} store_ww 旺旺
     * @apiParam {String} store_phone 手机
     * @apiParam {String} store_mainbusiness 主营商品
     * @apiParam {String} store_keywords SEO关键词
     * @apiParam {String} store_description SEO店铺描述
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function store_edit()
    {
        /**
         * 上传店铺图片
         */
        $store_banner = '';
        if (!empty($_FILES['store_banner']['name'])) {
            $upload_file = BASE_UPLOAD_PATH .DS. ATTACH_STORE.DS;
            $file_object = request()->file('store_banner');
            $file_name = $this->store_info['store_id'] . '_' . date('YmdHis') . rand(10000, 99999);
            $info = $file_object->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($upload_file, $file_name);
            if ($info) {
                $store_banner = $info->getFilename();
            }
            else {
                ds_json_encode(10001,$file_object->getError());
            }
        }

        //删除旧店铺图片
        if (!empty($store_banner) && !empty($this->store_info['store_banner'])) {
            @unlink(BASE_UPLOAD_PATH . DS . ATTACH_STORE . DS . $this->store_info['store_banner']);
        }
        /**
         * 更新入库
         */
        $param = array(
            'store_qq' => input('post.store_qq'), 'store_ww' => input('post.store_ww'), 'store_phone' => input('post.store_phone'),
            'store_mainbusiness' => input('post.store_mainbusiness'), 'store_keywords' => input('post.seo_keywords'),
            'store_description' => input('post.seo_description')
        );
        if (!empty($store_banner)){
            $param['store_banner'] = $store_banner;
        }
        

        $result = model('store')->editStore($param, array('store_id' => $this->store_info['store_id']));
        if (!$result) {
            ds_json_encode(10001,lang('ds_common_op_fail'));
        }
        ds_json_encode(10000, lang('ds_common_op_succ'),1);
    }

    /**
     * 店铺信息统计
     */
    public function store_statistics()
    {
        $stat_model = model('stat');
        $start_time = strtotime(date('Y-m', time()));        // 当月开始
        // 月销量 月订单
        $condition = array();
        $condition['order_add_time'] = array('gt', $start_time);
        $monthly_sales = $stat_model->getoneByStatorder($condition, 'COUNT(*) as ordernum,SUM(order_amount) as orderamount ');

        // 月访问量
        //确定统计分表名称
        $last_num = $this->store_info['store_id'] % 10; //获取店铺ID的末位数字
        $tablenum = ($t = intval(config('flowstat_tablenum'))) > 1 ? $t : 1; //处理流量统计记录表数量
        $flow_tablename = ($t = ($last_num % $tablenum)) > 0 ? "flowstat_$t" : 'flowstat';
        $condition = array();
        $condition['store_id'] = $this->store_info['store_id'];
        
        if($flow_tablename=='flowstat'){
            $condition['flowstat_stattime'] = array('gt', $start_time);
            $condition['flowstat_type'] = 'sum';
        }else{
            $condition['flowstat_stattime'] = array('gt', $start_time);
            $condition['flowstat_type'] = 'sum';
        }
        $statlist_tmp = $stat_model->getoneByFlowstat($flow_tablename, $condition, 'SUM(flowstat_clicknum) as amount');

        $output = array(
            'store_name' => $this->store_info['store_name'],
            'store_banner' => get_store_logo($this->store_info['store_banner'], 'store_logo'),
            'order_amount' => $monthly_sales['orderamount'], 'order_num' => $monthly_sales['ordernum'],
            'click_amount' => $statlist_tmp['amount']
        );
        ds_json_encode(10000, '',array('statistics' => $output));
    }

	/**
	 * 数据中心
	 */
	public function data_center()
	{
		$evaluatestore_model = model('evaluatestore');
		$data=$evaluatestore_model->getEvaluatestoreInfoByStoreID($this->store_info['store_id'], $this->store_info['storeclass_id']);
		$data['level']= $this->store_grade;

		ds_json_encode(10000,"查询成功",$data);
    }

	/**
	 * 交易数据
	 */
	public function data_transaction()
	{
		$type=input('param.type',0,'intval');//类型  1 实时 2日报  3 周报 4月报
		$start_time=input('param.start_time',0);//开始时间
		$end_time=input('param.end_time',0);//结束时间

		if($start_time > $end_time){
			ds_json_encode(10001,"开始时间不能大于等于结束时间");
		}
		$start_time=$start_time?$start_time:strtotime(date('Y-m-d',time()));
		$end_time=$end_time?$end_time:time();
		$stime =$start_time;
		$etime =$end_time;
		$stat_model = model('stat');

		////统计的日期0点
		$old_stat_time = strtotime(date('Y-m-d',time()));//昨天零时
		$old_end_time = time();//昨天零时
		if($type ==1){

		}elseif($type ==2){
			$old_stat_time=strtotime(date('Y-m-d',$start_time))-86400;//前天零时
			$old_end_time = $old_stat_time - 1;//前天23:59
		}elseif($type ==3){
			$date=$start_time;  //当前日期
			$first=1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
			$w=date('w',strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
			$now_start=date('Y-m-d',strtotime("$date -".($w ? $w - $first : 6).' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
			$old_stat_time=date('Y-m-d',strtotime("$now_start - 7 days"));  //上周开始日期
			$old_end_time=date('Y-m-d',strtotime("$now_start - 1 days"));  //上周结束日期
		}elseif($type ==4){
			$old_stat_time=mktime(0, 0, 0, date('m',$start_time)-1,1, date('Y',$start_time));//上个月的时间
			$old_end_time=mktime(0, 0, 0, date('m',$start_time),1, date('Y',$start_time))-1;//上个月的时间
		}else{
			ds_json_encode(10001,"参数错误");
		}

		//访客数
		$caller_where=[
			'type'=>1,
			'store_id'=>$this->store_info['store_id'],
			'c_id'=>$this->store_info['store_id'],
			'create_time'=>[['egt',$start_time],['lt',$end_time]]
		];
		$caller=model('storecaller')->where($caller_where)->sum('num');
		$caller_old_where=[
			'type'=>1,
			'store_id'=>$this->store_info['store_id'],
			'c_id'=>$this->store_info['store_id'],
			'create_time'=>[['egt',$old_stat_time],['lt',$old_end_time]]
		];
		//上个的信息
		$caller_old=model('storecaller')->where($caller_old_where)->sum('num');
		//上个月的比例
		if($caller_old ==0){
			$caller_round=0;
		}else{
			$caller_round=round(($caller/$caller_old) * 100,2);
		}



		$statnew_arr = array();

		//查询订单表下单量、下单金额、下单客户数
		$where = array();
		$where['order_isvalid'] = 1;//计入统计的有效订单
		$where['store_id'] = $this->store_info['store_id'];
		$where['order_add_time'] = array('between',array($stime,$etime));
		$field = ' COUNT(*) as ordernum, SUM(order_amount) as orderamount, COUNT(DISTINCT buyer_id) as ordermembernum, AVG(order_amount) as avgorderamount ';
		$stat_order = $stat_model->getoneByStatorder($where, $field);
		$statnew_arr['ordernum'] = ($t = $stat_order['ordernum'])?$t:0;//订单数量
		$statnew_arr['orderamount'] = ds_price_format(($t = $stat_order['orderamount'])?$t:(0));//订单金额
		$statnew_arr['ordermembernum'] = ($t = $stat_order['ordermembernum']) > 0?$t:0;//下单客数量
		$statnew_arr['avgorderamount'] = ds_price_format(($t = $stat_order['avgorderamount'])?$t:(0));//平均下单金额
		unset($stat_order);

		//上个的
		$old_statnew_arr=[];
		$where = array();
		$where['order_isvalid'] = 1;//计入统计的有效订单
		$where['store_id'] = $this->store_info['store_id'];
		$where['order_add_time'] = array('between',array($old_stat_time,$old_end_time));
		$field = ' COUNT(*) as ordernum, SUM(order_amount) as orderamount, COUNT(DISTINCT buyer_id) as ordermembernum, AVG(order_amount) as avgorderamount ';
		$stat_order = $stat_model->getoneByStatorder($where, $field);
		$old_statnew_arr['ordernum'] = ($t = $stat_order['ordernum'])?$t:0;//订单数量
		$old_statnew_arr['orderamount'] = ds_price_format(($t = $stat_order['orderamount'])?$t:(0));//订单金额
		$old_statnew_arr['ordermembernum'] = ($t = $stat_order['ordermembernum']) > 0?$t:0;//下单客数量
		$old_statnew_arr['avgorderamount'] = ds_price_format(($t = $stat_order['avgorderamount'])?$t:(0));//平均下单金额
		$ordernum_round=0;//订单数量比
		if($old_statnew_arr['ordernum']){
			$ordernum_round=round(($statnew_arr['ordernum']/$old_statnew_arr['ordernum']) * 100,2);
		}

		$orderamount_round=0;//订单金额比

		if(!empty($old_statnew_arr['orderamount'] * 100)){
			$orderamount_round=round(($statnew_arr['orderamount']/$old_statnew_arr['orderamount']) * 100,2);
		}

		$refundreturn_model = db('refundreturn');
		$condition = array();
		$condition['store_id'] = $this->store_info['store_id'];
		$condition['order_lock'] = 2;
		$condition['refund_state'] =3;
		$condition['add_time'] = array('between',array($stime,$etime));
		$refund_money = round($refundreturn_model->where($condition)->sum('refund_amount'),2);

		$condition = array();
		$condition['store_id'] = $this->store_info['store_id'];
		$condition['order_lock'] = 2;
		$condition['refund_state'] =3;
		$condition['add_time'] = array('between',array($old_stat_time,$old_end_time));
		$old_refund_money = $refundreturn_model->where($condition)->sum('refund_amount');
		$refund_money_round=0;
		if(($old_refund_money * 100)>0){
			$refund_money_round=round(($refund_money/$old_refund_money) * 100,2);
		}

		$data=[
			'caller'=>$caller,
			'caller_round'=>(string)$caller_round,
			'ordernum'=>$statnew_arr['ordernum'],
			'ordernum_round'=>(string)$ordernum_round,
			'orderamount'=>(string)$statnew_arr['orderamount'],
			'orderamount_round'=>(string)$orderamount_round,
			'refund_money'=>(string)$refund_money,
			'refund_money_round'=>(string)$refund_money_round,
		];
		ds_json_encode(10000, '',$data);

    }

	/**
	 * 流量
	 */
	public function data_flow()
	{
		$data_type=input('data_type',1,'intval');// 1:店铺访客量 2店铺浏览量 3 商品浏览量 4 支付转化率
		$type=input('type',0,'intval');//0:是七天 1:30天
		$end_time=time();
		if($type != 1){
			//周


			$search_type='week';
			$first=1;
			$time=strtotime(date('Y-m-d'))+3600 * 24;
			$start_time=$time - 7 * 3600 * 24;//本周时间

		}else{
			//月
			$search_type='month';
			$time=strtotime(date('Y-m-d'))+3600 * 24;
			$start_time=$time - 30 * 3600 * 24;//本周时间
		}
		$store_id = $this->store_info['store_id'];
		//确定统计分表名称
		$last_num = $store_id % 10; //获取店铺ID的末位数字
		$tablenum = ($t = intval(config('flowstat_tablenum'))) > 1 ? $t : 1; //处理流量统计记录表数量

		$days = intval(abs(($time-$start_time)/86400));
		$stat_model = model('stat');

		for($i=0; $i<$days; $i++){

			$day_t = date('Y-m-d',$start_time+$i*86400);
			$statlist[$day_t] = 0;


		}
		//店铺浏览量
		if($data_type == 1){
			$where = array();
			$where['store_id'] = $store_id;
			$where['c_id'] = $store_id;
			$where['type'] =1;
			$where['create_time'] = array('between',[$start_time,$end_time]);
			$field = ' SUM(num) as amount';
			if($search_type == 'week'){

				$field .= ' ,date(FROM_UNIXTIME(create_time)) as timeval ';
			}
			if($search_type == 'month'){
				$field .= ' ,date(FROM_UNIXTIME(create_time)) as timeval ';
			}
			$flow_tablename="storecaller";
		}elseif($data_type == 2){
			$where = array();
			$where['store_id'] = $store_id;
			$where['flowstat_stattime'] = array('between',[$start_time,$end_time]);
			$where['flowstat_type'] = 'sum';

			$field = ' SUM(flowstat_clicknum) as amount';

			if($search_type == 'week'){

				$field .= ' ,date(FROM_UNIXTIME(flowstat_stattime)) as timeval ';
			}
			if($search_type == 'month'){
				$field .= ' ,date(FROM_UNIXTIME(flowstat_stattime)) as timeval ';
			}

			$flow_tablename = ($t = ($last_num % $tablenum)) > 0 ? "flowstat_$t" : 'flowstat';
		}elseif($data_type == 3){
			$where = array();
			$where['store_id'] = $store_id;
			$where['flowstat_stattime'] = array('between',[$start_time,$end_time]);
			$where['flowstat_type'] = 'goods';

			$field = ' goods_id,SUM(flowstat_clicknum) as amount';
			if($search_type == 'week'){

				$field .= ' ,date(FROM_UNIXTIME(flowstat_stattime)) as timeval ';
			}
			if($search_type == 'month'){
				$field .= ' ,date(FROM_UNIXTIME(flowstat_stattime)) as timeval ';
			}
			$flow_tablename = ($t = ($last_num % $tablenum)) > 0 ? "flowstat_$t" : 'flowstat';
		}elseif($data_type == 4){
			/**
			 * 订单成交数量
			 */
			$order_where=[
				'order_state'=>['in',['20','30','40']],
				'refund_state'=>['in',['0','1']],
				'delete_state'=>0,
				'store_id'=>$this->store_info['store_id'],
				'add_time'=>array('between',[$start_time,$end_time])
			];


			$vrorder_where=[
				'order_state'=>['in',['20','40']],
				'refund_state'=>['in',['0','1']],
				'delete_state'=>0,
				'store_id'=>$this->store_info['store_id'],
				'add_time'=>array('between',[$start_time,$end_time])
			];

			$zongorder_where=[
				'refund_state'=>['in',['0','1']],
				'delete_state'=>0,
				'store_id'=>$this->store_info['store_id'],
				'add_time'=>array('between',[$start_time,$end_time])
			];

			$zongvrorder_where=[
				'refund_state'=>['in',['0','1']],
				'delete_state'=>0,
				'store_id'=>$this->store_info['store_id'],
				'add_time'=>array('between',[$start_time,$end_time])
			];
			$field = ' count(*) as amount';
			$field .= ' ,date(FROM_UNIXTIME(add_time)) as timeval ';
			$flow_tablename='order';
			$order_count = $stat_model->statByFlowstat($flow_tablename, $order_where, $field, 0, 0, 'timeval asc', 'timeval');
			$zongorder_count = $stat_model->statByFlowstat($flow_tablename,$zongorder_where, $field, 0, 0, 'timeval asc', 'timeval');
			$vrflow_tablename='order';
			$vrorder_count = $stat_model->statByFlowstat($vrflow_tablename, $vrorder_where, $field, 0, 0, 'timeval asc', 'timeval');
			$zongvrorder_count = $stat_model->statByFlowstat($vrflow_tablename, $zongvrorder_where, $field, 0, 0, 'timeval asc', 'timeval');
			$all_1_data=[];
			$all_2_data=[];
			$all_3_data=[];
			$all_4_data=[];
			foreach($order_count as $order_count_v){
				$all_1_data[$order_count_v['timeval']]=$order_count_v['amount'];
			}
			foreach($zongorder_count as $zongorder_count_v){
				$all_2_data[$zongorder_count_v['timeval']]=$zongorder_count_v['amount'];
			}
			foreach($vrorder_count as $vrorder_count_v){
				$all_3_data[$vrorder_count_v['timeval']]=$vrorder_count_v['amount'];
			}
			foreach($zongvrorder_count as $zongvrorder_count_v){
				$all_4_data[$zongvrorder_count_v['timeval']]=$zongvrorder_count_v['amount'];
			}
		}
		if($data_type != 4){
			$statlist_tmp = $stat_model->statByFlowstat($flow_tablename, $where, $field, 0, 0, 'timeval asc', 'timeval');
			if ($statlist_tmp){
				foreach((array)$statlist_tmp as $k=>$v){
					$statlist[$v['timeval']] = floatval($v['amount']);
				}
			}
		}else{
			$statlist_data=[];
			if ($statlist){
				foreach((array)$statlist as $k=>$v){
					$order_v=0;
					$zongorder_v=0;
					if(isset($all_1_data[$k])){
						$order_v+=$all_1_data[$k];
					}

					if(isset($all_2_data[$k])){
						$zongorder_v+=$all_2_data[$k];
					}

					if(isset($all_3_data[$k])){
						$order_v+=$all_3_data[$k];
					}
					if(isset($all_4_data[$k])){
						$zongorder_v+=$all_4_data[$k];
					}
					//var_dump($zongorder_v);
					//var_dump($order_v);
					//$statlist_data[$k] = (string)(($order_v/$zongorder_v) * 100);
					if(!empty(intval($zongorder_v))){

						$statlist_data[$k] = (string)round(($order_v/$zongorder_v) * 100,2);
					}else{
						$statlist_data[$k] =  (string)0;
					}

				}

			}
			$statlist=$statlist_data;
		}




		//访客数
		$caller_where=[
			'store_id'=>$this->store_info['store_id'],
			'c_id'=>$this->store_info['store_id'],
			'type'=>1,
			'create_time'=>[['egt',$start_time],['lt',$end_time]]
		];
		$caller=model('storecaller')->where($caller_where)->sum('num');

		//浏览量
		$field_tmp=' SUM(flowstat_clicknum) as amount';
		$flow_tablename_tmp = ($t = ($last_num % $tablenum)) > 0 ? "flowstat_$t" : 'flowstat';
		$where = array();
		$where_like['store_id'] = $store_id;
		$where_like['flowstat_stattime'] = array('between',[$start_time,$end_time]);
		$where_like['flowstat_type'] = 'sum';
		$statlist_like = $stat_model->statByFlowstat($flow_tablename_tmp, $where_like, $field_tmp, 0, 0, 'flowstat_clicknum asc', 'flowstat_clicknum');
		$statlist_like_num=array_sum(array_column($statlist_like, 'amount'));

		//商品预览量
		$field_tmp=' SUM(flowstat_clicknum) as amount';
		$flow_tablename_tmp = ($t = ($last_num % $tablenum)) > 0 ? "flowstat_$t" : 'flowstat';
		$where = array();
		$where_like['store_id'] = $store_id;
		$where_like['flowstat_stattime'] = array('between',[$start_time,$end_time]);
		$where_like['flowstat_type'] = 'goods';
		$statlist_goods = $stat_model->statByFlowstat($flow_tablename_tmp, $where_like, $field_tmp, 0, 0, 'flowstat_clicknum asc', 'flowstat_clicknum');
		$statlist_goods_num=array_sum(array_column($statlist_goods, 'amount'));



		/**
		 * 订单成交数量
		 */
		$order_where=[
			'order_state'=>['in',['20','30','40']],
			'refund_state'=>['in',['0','1']],
			'delete_state'=>0,
			'store_id'=>$this->store_info['store_id'],
			'add_time'=>array('between',[$start_time,$end_time])
		];


		$vrorder_where=[
			'order_state'=>['in',['20','40']],
			'refund_state'=>['in',['0','1']],
			'delete_state'=>0,
			'store_id'=>$this->store_info['store_id'],
			'add_time'=>array('between',[$start_time,$end_time])
		];
		$order_count=model('order')->getOrderNum($order_where);
		$vrorder_count=model('Vrorder')->getOrderNum($vrorder_where);
		$wan_order_count=$vrorder_count+$order_count;
		unset($vrorder_where['order_state'],$order_where['order_state']);
		$zong_order_count=model('order')->getOrderNum($order_where);
		$zong_vrorder_count=model('Vrorder')->getOrderNum($vrorder_where);
		$zong_order_count_1=$zong_order_count+$zong_vrorder_count;
		if((float)$zong_order_count_1>0){
			$success=round(($wan_order_count/$zong_order_count_1) * 100,2);
		}else{
			$success=0;
		}

		$data=[
			'statlist'=>array_values($statlist),
			//'statlist'=>$statlist,
			'caller'=>$caller,
			'statlist_like_num'=>$statlist_like_num,
			'statlist_goods_num'=>$statlist_goods_num,
			'success'=>(string)$success
		];

		ds_json_encode(10000,"查询成功",$data);



    }


	/**
	 * 数据中心  商品
	 */
	public function data_product()
	{
		//浏览量
		$type=input('type',1,'intval');//类型 1 浏览量  2访客数 3支付转化 4 收藏数
		$page_size=input('page_size',10,'intval');//类型 页数
		$stat_model = model('stat');
		if($type ==1){

			//获得搜索的开始时间和结束时间
			$where = array();
			$where['store_id'] = $this->store_info['store_id'];
			$where['flowstat_type'] = 'goods';

			$field = ' goods_id,SUM(flowstat_clicknum) as amount';

			//确定统计分表名称
			$last_num = $this->store_info['store_id'] % 10; //获取店铺ID的末位数字
			$tablenum = ($t = intval(config('flowstat_tablenum'))) > 1 ? $t : 1; //处理流量统计记录表数量
			$flow_tablename = ($t = ($last_num % $tablenum)) > 0 ? "flowstat_$t" : 'flowstat';
			$statlist_tmp = $stat_model->statByFlowstat($flow_tablename, $where, $field, 0, 30, 'amount desc,goods_id asc', 'goods_id');



		}elseif($type== 2){
			//商品访客数
			$caller_where=[
				'store_id'=>$this->store_info['store_id'],
				'type'=>2,
			];
			$flow_tablename ="storecaller";
			$field = ' c_id as goods_id,SUM(num) as amount';
			$statlist_tmp = $stat_model->statByFlowstat($flow_tablename, $caller_where, $field, 0, 30, 'amount desc,goods_id asc', 'goods_id');
		}elseif($type== 3){//支付转化
			ds_json_encode(10001,"暂无此功能");
		}elseif($type== 4){
			$where = array();
			$where['store_id'] = $this->store_info['store_id'];
			$where['fav_type'] = 'goods';
			$field = ' fav_id as goods_id,count(*) as amount';

			//确定统计分表名称
			$flow_tablename='favorites';
			$statlist_tmp = $stat_model->statByFlowstat($flow_tablename, $where, $field, 0, 30, 'amount desc,goods_id asc', 'goods_id');

		}else{
			ds_json_encode(10001,"参数错误");
		}

		if ($statlist_tmp){
			$goodsid_arr = array();
			$statlist_arr = array();
			foreach((array)$statlist_tmp as $k=>$v){
				$goodsid_arr[] = $v['goods_id'];
				$statlist_arr[$v['goods_id']]=$v['amount'];
			}
			//查询相应商品
			$goods_list_tmp = $stat_model->statByGoods(array('goods_id'=>array('in',$goodsid_arr)), $field = 'goods_name,goods_image,goods_id');
			foreach ((array)$goods_list_tmp as $k=>$v){
				$goods_list_tmp[$k]['goods_image'] = goods_cthumb($v['goods_image'], 480, $this->store_info['store_id']);

				if (isset($statlist_arr[$v['goods_id']])) {
					$goods_list_tmp[$k]['amount'] = floatval($statlist_arr[$v['goods_id']]);

				}else{
					$goods_list_tmp[$k]['amount']=0;
				}
			}

			$good_list=$goods_list_tmp;

		}else{
			$good_list=[];
		}

		ds_json_encode(10000,"查询成功",$good_list);
    }



	/**
	 * 数据中心  售后
	 */
	public function data_service()
	{
		//浏览量
		$data_type=input('data_type',1,'intval');//类型 1 纠纷退款  2退款 3平台介入 4 退款时长
		$type=input('type',0,'intval');//0:是七天 1:30天
		$end_time=time();
		if($type != 1){
			//周
			$search_type='week';
			$first=1;
			$time=strtotime(date('Y-m-d'))+3600 * 24;
			$start_time=$time - 7 * 3600 * 24;//本周时间

		}else{
			//月
			$search_type='month';
			$time=strtotime(date('Y-m-d'))+3600 * 24;
			$start_time=$time - 30 * 3600 * 24;//本周时间
		}
		$store_id = $this->store_info['store_id'];

		$days = intval(abs(($time-$start_time)/86400));
		$stat_model = model('stat');

		for($i=0; $i<$days; $i++){

			$day_t = date('Y-m-d',$start_time+$i*86400);
			$statlist[$day_t] = 0;
		}
		//店铺浏览量
		if($data_type == 1){
			ds_json_encode(10001,"暂未开放");
		}elseif($data_type == 2){//品质退款
			$where = array();
			$where['store_id'] = $store_id;
			$where['admin_time'] = array('between',[$start_time,$end_time]);
			$where['seller_state'] = '2';
			$where['refund_state'] = '3';


			$field = ' count(*) as amount';

			if($search_type == 'week'){

				$field .= ' ,date(FROM_UNIXTIME(admin_time)) as timeval ';
			}
			if($search_type == 'month'){
				$field .= ' ,date(FROM_UNIXTIME(admin_time)) as timeval ';
			}

			$flow_tablename = "refundreturn";
		}elseif($data_type == 3){
			ds_json_encode(10001,"暂未开放");
		}elseif($data_type == 4){//退款时长
			$where = array();
			$where['store_id'] = $store_id;
			$where['admin_time'] = array('between',[$start_time,$end_time]);
			$where['seller_state'] = '2';
			$where['refund_state'] = '3';


			$field = ' avg(admin_time - add_time) as amount';

			if($search_type == 'week'){

				$field .= ' ,date(FROM_UNIXTIME(admin_time)) as timeval ';
			}
			if($search_type == 'month'){
				$field .= ' ,date(FROM_UNIXTIME(admin_time)) as timeval ';
			}

			$flow_tablename = "refundreturn";
		}

		$statlist_tmp = $stat_model->statByFlowstat($flow_tablename, $where, $field, 0, 0, 'timeval asc', 'timeval');
		//echo $stat_model->getLastSql();exit;
		if ($statlist_tmp){
			foreach((array)$statlist_tmp as $k=>$v){
				$statlist[$v['timeval']] = floatval($v['amount']);
			}
		}





		//访客数
		$whererefund = array();
		$whererefund['store_id'] = $store_id;
		$whererefund['admin_time'] = array('between',[$start_time,$end_time]);
		$whererefund['seller_state'] = '2';
		$whererefund['refund_state'] = '3';

		$refundreturn_num=model('refundreturn')->getRefundreturnCount($whererefund);

		//访客数
		$whererefund = array();
		$whererefund['store_id'] = $store_id;
		$whererefund['admin_time'] = array('between',[$start_time,$end_time]);
		$whererefund['seller_state'] = '2';
		$whererefund['refund_state'] = '3';

		$refundreturn_time=model('refundreturn')->field("avg((admin_time - add_time)) as timeavg")->where($whererefund)->find();

		$data=[
			'statlist'=>array_values($statlist),
			//'statlist'=>$statlist,
			'refundreturn_num'=>$refundreturn_num,
			'refundreturn_time'=>secondChanage(intval($refundreturn_time['timeavg'])),
			//'statlist_goods_num'=>$statlist_goods_num,
			//'success'=>(string)$success
		];

		ds_json_encode(10000,"查询成功",$data);
	}
}